package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet_service.entity.Role;
import com.pet_service.entity.User;
import com.pet_service.enums.TUserRegisterTypeStatus;
import com.pet_service.enums.TUserStatus;
import com.pet_service.result.Result;
import com.pet_service.service.RoleService;
import com.pet_service.service.UserService;
import com.pet_service.upload.AvatarUploadUtil;
import com.pet_service.util.EnumUtils;
import com.pet_service.vo.GrantRoleBean;
import com.pet_service.vo.PageBean;
import com.pet_service.vo.PasswordBean;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Slf4j
@Tag(name = "用户接口")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    //分页查询用户列表
    @PostMapping("/list")
     //拥有查询权限才可以访问次方法
    @PreAuthorize("hasAuthority('system:user:view')")
    public Result userList(@RequestBody PageBean pageBean) {
        log.info("分页查询用户列表,参数:{}", pageBean);
        //mybatis-plus提供一个page方法帮助分页
        Page<User> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        //创建查询条件,QueryWrapper是MyBatis-Plus提供的条件构造器，可以方便地构建各种查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //模糊查询,如果pageBean.getQuery()不为null，则对username字段进行模糊匹配
        queryWrapper.like(pageBean.getQuery()!=null,"username",pageBean.getQuery().trim());
        //分页查询
        IPage<User> iPage = userService.page(page,queryWrapper);
        //获取页面显示的数据
        List<User> userList=iPage.getRecords();
        //把每个用户拥有的角色查询出来
        for (User user : userList){
            List<Role> roleList=roleService.getRoleListByUserId(user.getId());
            user.setRoleList(roleList);
        }
        //重置设置到iPage对象中
        //setRecords作用是设置分页查询结果
        iPage.setRecords(userList);
        return Result.ok(iPage);
    }

    //新增或修改用户
    //新增或修改用户
    @PostMapping("/saveOrUpdateUser")
    @PreAuthorize("hasAuthority('system:user:create')" + "||" + "hasAuthority('system:user:edit')")
    public Result savaOrUpdateUser(@RequestBody User user) {
        // 检查QQ openid是否已存在（排除当前用户自身）
        if (user.getQq_openid() != null && !user.getQq_openid().isEmpty()) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("qq_openid", user.getQq_openid());
            if (user.getId() != null && user.getId() > 0) {
                // 更新操作时排除自己
                queryWrapper.ne("id", user.getId());
            }
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return Result.fail("该QQ账号已被其他用户绑定！");
            }
        }

        // 检查微信 openid是否已存在（排除当前用户自身）
        if (user.getWechat_openid() != null && !user.getWechat_openid().isEmpty()) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("wechat_openid", user.getWechat_openid());
            if (user.getId() != null && user.getId() > 0) {
                // 更新操作时排除自己
                queryWrapper.ne("id", user.getId());
            }
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return Result.fail("该微信账号已被其他用户绑定！");
            }
        }

        // 检查手机号是否已存在（排除当前用户自身）
        if (user.getPhone() != null && !user.getPhone().isEmpty()) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", user.getPhone());
            if (user.getId() != null && user.getId() > 0) {
                // 更新操作时排除自己
                queryWrapper.ne("id", user.getId());
            }
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return Result.fail("该手机号已被其他用户绑定！");
            }
        }

        if(user==null || user.getId()==0){
            //新增用户
            //对密码加密
            BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
            user.setPassword(encoder.encode(user.getPassword()));

            // 设置默认注册类型为账号密码
            if (user.getRegister_type() == null) {
                user.setRegister_type(TUserRegisterTypeStatus.ACCOUNT_PASSWORD);
            }
        }
        user.setUpdated_at(new Date());//设置更新时间
        boolean flag=userService.saveOrUpdate(user);
        return flag ? Result.ok("修改成功!") : Result.fail("修改失败!");
    }



    //检查用户名是否重复
    //@PathVariable注解表示从路径中获取参数
    @GetMapping("/checkUserName/{username}")
    @PreAuthorize("hasAuthority('system:user:view')")
    public Result checkUserName(@PathVariable("username") String username) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("username", username);
//        User user = userService.getOne(queryWrapper);
        //Mybatis-Plus的查询会自带is_delete=0,不会检查被删除过的数据,可能会导致新用户还能使用旧的属性
        return userService.checkUserName( username);
    }

    //验证手机号是否重复
    //@PreAuthorize注解表示当前用户必须具有指定的权限才能访问此方法
    //("hasAuthority('system:user:view')")是一个权限表达式，表示当前用户必须具有system:user:view权限才能访问此方法
    @GetMapping("/checkUserPhone/{userPhone}")
    @PreAuthorize("hasAuthority('system:user:view')")
    public Result checkUserPhone(@PathVariable("userPhone") String userPhone) {
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("phone", userPhone);
//        User user = userService.getOne(queryWrapper);
        return userService.checkUserPhone(userPhone);
    }

    //根据用户id获取用户详细信息
    @GetMapping("/getUser/{userId}")
    @PreAuthorize("hasAuthority('system:user:view')")
    public Result getUser(@PathVariable("userId") Long userId) {
        User user = userService.getById(userId);
        return Result.ok(user);
    }

    //删除用户
    @DeleteMapping
    //需要检查权限表是否有这个权限
    @PreAuthorize("hasAuthority('system:user:delete')")
    public Result deleteUser(@RequestBody List<Integer> ids) {
       //于快速创建一个固定大小的 List,不能进行add和delete，而且与原数组同步
        log.info("删除用户,参数:{}", Arrays.asList(ids));
        return userService.removeByUserIdList(ids);
    }

    //分配角色
    @PostMapping("/grantRole")
    //permission表中 分配角色的权限
    @PreAuthorize("hasAuthority('system:user:role')")
    @Operation(summary = "分配角色")
    public Result grantRole( @Parameter(description = "分配角色")@RequestBody GrantRoleBean grantRoleBean){
        log.info("分配角色,参数:{}", grantRoleBean);
        Result result=userService.grantRole(grantRoleBean);
        log.info("分配角色,返回数据:{}", result);
        return result;
    }

    //更新用户状态
    @GetMapping("updateState/{userId}/{status}")
    @PreAuthorize("hasAuthority('system:user:edit')")//需要检查权限表是否有这个权限
    public Result updateState(
            @PathVariable("userId")Integer userId,
            @PathVariable("status") Integer status
    ){
        //根据id找到sysuser对象
        User sysuser = userService.getById(userId);

        // 使用工具类方法
        TUserStatus userStatus = EnumUtils.getEnumByCode(TUserStatus.class, status);
        if (userStatus == null) {
            return Result.fail("无效的用户状态值: " + status);
        }

        //修改状态 , 0 禁用  1 启用
        sysuser.setStatus(userStatus);
        sysuser.setUpdated_at(new Date());
        boolean flag=userService.updateById(sysuser);
        return flag ? Result.ok("状态更新成功!") : Result.fail("状态更新失败!");
    }

    //更新用户信息
    @PostMapping("/updateBaseInfo")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result updateBaseInfo(@RequestBody User user) {
        return userService.updateBaseInfo(user);
    }

    //检查旧密码
    @PostMapping("/checkOldPwd")
    @PreAuthorize("hasAuthority('system:user:view')")
    public Result checkOldPwd(@RequestBody PasswordBean passwordBean) {
        //根据id获取用户信息
        User user = userService.getById(passwordBean.getId());
        //判断旧密码是否正确
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        //passwordBean.getOldPassword() 传入的明文密码
        boolean matches = encoder.matches( passwordBean.getOldPassword(), user.getPassword());
        return matches ? Result.ok("密码正确") : Result.fail("密码错误");
    }

    //修改密码
    @PostMapping("/updatePwd")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result updatePwd(@RequestBody PasswordBean passwordBean) {
        return userService.updatePassword(passwordBean);
    }

    //上传图片
    @PostMapping("/uploadImage")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result uploadImage(@RequestParam("userId") Integer userId,
                              @RequestParam("file") MultipartFile file){
        log.info("上传文件:{}", file.getOriginalFilename());
        //先删除用户原来的头像
        AvatarUploadUtil.deleteAvatar("petservice", userService.getById(userId).getAvatar_url());
        String avatar_url = AvatarUploadUtil.uploadAvatar("petservice", file);
        return avatar_url == null ? Result.fail(500,"上传失败!"): Result.ok(avatar_url) ;
    }

    //修改头像
    @PostMapping("/editImage")
    @PreAuthorize("hasAuthority('system:user:edit')")
    public Result editImage(@RequestBody User user) {
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("avatar_url", user.getAvatar_url());
        updateWrapper.eq("id", user.getId());
        boolean flag = userService.update(updateWrapper);
        return flag ? Result.ok("头像更新成功!") : Result.fail("头像更新失败!");
    }

    //分页查询客户列表
    @PostMapping("/customers/list")
    @PreAuthorize("hasAuthority('customer:info:view')")
    public Result customerList(@RequestBody PageBean pageBean) {
        log.info("分页查询客户列表, query={}", pageBean.getQuery());

        Page<User> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());
        IPage<User> iPage = userService.pageByRoleCode(page, "CUSTOMER", pageBean.getQuery());

        // 加载角色信息
        for (User user : iPage.getRecords()) {
            List<Role> roles = roleService.getRoleListByUserId(user.getId());
            user.setRoleList(roles);
        }

        return Result.ok(iPage);
    }
}
